const Router = require('koa-router')
const router = new Router();
const { returnMsg, queryFn } = require("../../config")
// 导入 bcryptjs 这个包
const bcrypt = require('bcryptjs')
// 引入发送邮件的模块
const nodemailer = require('nodemailer')
const moment = require('moment')
const smtpTransport = require('nodemailer-smtp-transport')

const transport = nodemailer.createTransport(smtpTransport({
    host: 'smtp.163.com', // 服务 由于我用的163邮箱
    port: 465, // smtp端口 默认无需改动
    secure: true,
    auth: {
        user: 'zy1276046082@163.com', // 用户名
        pass: 'XBKRLMWBMLRWYKKL' // SMTP授权码
    }
}));

const randomFns = () => { // 生成6位随机数
    let code = ""
    for (let i = 0; i < 6; i++) {
        code += parseInt(Math.random() * 10)
    }
    return code
}
const regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ //验证邮箱正则
const regPassword = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,18}$/ //密码邮箱正则
const regUsername = /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{4,16}$/ // 账户正则所以通过req.body获取用户提交的邮箱


router.post("/verification", async ctx => {
    let EMAIL = ctx.request.body.e_mail //req为请求体对象 我使用的是post请求方式，
    if (regEmail.test(EMAIL) ) {  //邮箱验证通过
        // 验证邮箱是否已经添加
        let sql4 = `select id from user where email = '${EMAIL}'`
        let result4 =await queryFn(sql4)
        if(result4.length = 0){
            ctx.body = returnMsg(2, "发送验证码失败！", '该邮箱还未注册用户')
            return
        }
        let code = randomFns()
        await new Promise((res, rej) => {
            transport.sendMail({
                from: 'zy1276046082@163.com', // 发件邮箱
                to: EMAIL, // 收件列表
                subject: '验证你的电子邮件', // 标题
                html: `
                <p>你好！</p>
                <p>您正在执行修改CMS后台密码操作，如非本人操作，请及时检查帐号邮箱绑定并修改密码。</p>
                <p>你的验证码是：<strong style="color: #ff4e2a;">${code}</strong></p>
                <p>***该验证码5分钟内有效***</p>` // html 内容
                },
                 async (error, data)=> {
                    let mydate = moment().format('YYYY-MM-DD hh:mm:ss')
                    let sql1 = `insert into verification value (null, '${code}', '${mydate}')`
                    let result = await queryFn(sql1)
                    let sql2 = `select id from verification where date = '${mydate}'`
                    let result2 = await queryFn(sql2)
                    if(result2.length>0){
                        setTimeout(() => {
                            sql3 = `delete from verification where id = '${result2[0].id}'`
                            queryFn(sql3)
                        }, 1000*60*5);
                        res(result2)
                    }else{
                        rej('验证码发送失败')
                    }
                    if (!isNaN(error) && error) {
                        rej(error)
                    }
                })
               
        }).then((result)=>{
            ctx.body = returnMsg(0, "验证码发送成功", result)
            }
        ).catch((error)=>{
            ctx.body = returnMsg(2, "发送验证码失败！", error)
            transport.close(); // 如果没用，关闭连接池
        })
    } else {
        ctx.body = returnMsg(2, "发送验证码失败！", '参数格式错误')
    }
})

router.post("/", async ctx => {
    let { password ,email,codeid,code} = ctx.request.body
    if(!( password && email  && codeid && code)){
        ctx.body = returnMsg(2, "修改密码失败", '参数错误')
        return
    }
    if (!regEmail.test(email)&& !regPassword.test(password) ){
        ctx.body = returnMsg(2, "修改密码失败", '参数格式错误')
        return
    }

    let sql4 = `select id from user where email = '${email}'`
    let result4 =await queryFn(sql4)
    if(result4.length = 0){
        ctx.body = returnMsg(2, "修改密码失败", '邮箱还未注册账号')
        return
    }

    let sql5 = `select code from verification where id = '${codeid}'`
    let result5 =await queryFn(sql5)
    if(result5.length <= 0){
        ctx.body = returnMsg(2, "修改密码失败", '验证码已失效')
        return
    }
    if(code != result5[0].code){
        ctx.body = returnMsg(2, "修改密码失败", '验证码错误')
        return
    }

    if (password) {
            /* 
                editable 表示是否编辑文章 0表示不允许编辑 1表示可以编辑
                player 字段是否时为管理员 admin vip表示管理员 normal表示普通用户 默认都是普通用户
            */

            let passwords = bcrypt.hashSync(password, 10)
            let sql1 = `UPDATE user SET password = '${passwords}' WHERE email = '${email}'`
            let result1 = await queryFn(sql1)
            if(result1.affectedRows>0){
                ctx.body = returnMsg(0, "修改成功")
            }
            let sql2 = `DELETE FROM verification WHERE id = '${codeid}'`
            let result2 = await queryFn(sql2)
            console.log(result2)
    } else {
        ctx.body = returnMsg(1, "请求失败", "参数有错误")
    }
})

module.exports = router